package com.ygg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ygg.exception.YyghException;
import com.ygg.listener.DictListener;
import com.ygg.mapper.DictMapper;
import com.ygg.model.cmn.Dict;
import com.ygg.result.Result;
import com.ygg.service.DictService;
import com.ygg.vo.cmn.DictEeVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
        implements DictService {


    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        List<Dict> dicts = this.query().eq("parent_id", id).list();

        for (Dict dict : dicts) {
            Integer count = this.query().eq("parent_id", dict.getId()).count();
            dict.setHasChildren(count > 0);
        }

        return dicts;

    }

    @Override
    public void exportDate(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<Dict> list = this.list();
            List<DictEeVo> dictEeVos = list.stream().map(k -> BeanUtil.copyProperties(k, DictEeVo.class)).collect(Collectors.toList());
            //这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).autoCloseStream(Boolean.FALSE).sheet("Dict")
                    .doWrite(dictEeVos);

        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }

    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDate(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getName(String dictCode, String value) {
//        Dict dict = this.query().eq(!StringUtils.isEmpty(dictCode), "dict_code", dictCode)
//                .eq(value != null, "value", value).one();
//        return dict.getName();

        if (StringUtils.isEmpty(dictCode)) {
            Dict dict1 = this.query().eq("value", value).one();
            return dict1.getName();
        } else {
            Dict dict2 = this.query().eq("dict_code", dictCode).one();
            Long pid = dict2.getId();
            Dict dict3 = this.query().eq("parent_id", pid)
                    .eq("value", value).one();
            return dict3.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict one = this.query().eq("dict_code", dictCode).one();

        return this.findChlidData(one.getId());

    }


}
